package com.zhanghe.study.java8.dll;

import com.sun.jna.Memory;
import com.sun.jna.Pointer;

import java.util.ArrayList;
import java.util.List;

public class VectorConverter {

    // 将List<TCLineInfo>转换为Pointer
    public static Pointer toPointer(List<TCLineInfo> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        Memory memory = new Memory(list.size() * TCLineInfo.SIZE);
        for (int i = 0; i < list.size(); i++) {
            TCLineInfo info = list.get(i);
            memory.setPointer(i * TCLineInfo.SIZE, info.getPointer());
        }
        return memory;
    }

    // 将Pointer转换为List<TCLineInfo>
    public static List<TCLineInfo> fromPointer(Pointer pointer, int size) {
        List<TCLineInfo> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            TCLineInfo info = new TCLineInfo.ByReference();
            info.read(pointer.share(i * TCLineInfo.SIZE, TCLineInfo.SIZE));
            list.add(info);
        }
        return list;
    }

    // 将byte[]转换为Pointer
    public static Pointer toPointer(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        Memory memory = new Memory(bytes.length);
        memory.write(0, bytes, 0, bytes.length);
        return memory;
    }

    // 将Pointer转换为byte[]
    public static byte[] fromPointerByte(Pointer pointer, int size) {
        byte[] bytes = new byte[size];
        pointer.read(0, bytes, 0, size);
        return bytes;
    }
}